/*
 * @Description: 授权、登录工具类
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2023-11-1
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2024-04-24
 */

import { requestLogin } from '@/api/system/ysys-user/account'
import { AuthTypeEnum } from '@/api/system/ysys-user/account/enum'
import { requestGetUserInfoByUserId } from '@/api/system/ysys-user/user'
import { HttpCodeEnum } from '@/enum/httpEnum'
import { LOGIN_PAGE } from '@/enum/pageEnum'
import { useUserInfoStore } from '@/stores/userInfo'
import { getUserId, saveLoginCode, saveOpenid, saveRefreshToken, saveToken, saveUserId } from '@/utils/storage'

/**
 * 微信授权（获取openid、token，以及userInfo）
 */
export const wxAuth = async () => {
  return new Promise<void>((resolve, reject) => {
    uni.login({
      success: async (e: UniApp.LoginRes) => {
        const { errMsg, code } = e
        if (errMsg === 'login:ok') await saveOpenidAndToken(code)
        resolve()
      },
      error: () => reject(),
    })
  })
}

/**
 * 保存token、openid、userId至localStorage中
 * @param wxCode wx.login返回的code
 */
export const saveOpenidAndToken = async (wxCode: string) => {
  const { responseCode, responseData } = await requestLogin({ wxCode, authType: AuthTypeEnum.XCX }, { errTip: false })
  if (responseCode === HttpCodeEnum.ERROR_NO_AUTHPHONE) {
    // openid未绑定用户：将code缓存起来，供绑定手机号接口（authPhone）调用
    const { code } = responseData
    if (code) saveLoginCode(code)
  } else if (responseCode === HttpCodeEnum.SUCCESS) {
    // openid已绑定用户：token、openId、userId存储至storage中；userInfo存储至userInfoStore中
    const { openId, userId, token, refreshToken } = responseData
    saveOpenid(openId)
    saveUserId(userId)
    saveToken(token)
    saveRefreshToken(refreshToken)
    await saveUserInfo()
  }
}

/**
 * 保存用户信息至userInfoStore中
 */
export const saveUserInfo = async () => {
  const { responseData } = await requestGetUserInfoByUserId({ userId: getUserId() })
  const userInfoStore = useUserInfoStore()
  userInfoStore.setUserInfo(responseData)
}

/**
 * 校验是否登录
 * @returns
 */
export const checkLogin = () => {
  const userInfoStore = useUserInfoStore()
  return userInfoStore.isPhoneBind
}

/**
 * 校验是否登录（未登录跳转登录）
 * @returns
 */
export const validLogin = () => {
  if (!checkLogin()) {
    uni.navigateTo({ url: LOGIN_PAGE })
    return false
  }
  return true
}
